import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:source_gen/source_gen.dart';

import '../annotations/JsonGeneratorTest.dart';

/// 注解解析
class TestGenerator extends GeneratorForAnnotation<JsonGeneratorTest> {
  @override
  generateForAnnotatedElement(
      Element element, ConstantReader annotation, BuildStep buildStep) {
    _analyseBuildStep(buildStep);
    _analyseAnnotation(annotation);
    _analyseElement(element);
    return template("_\$${element.name}", "Gen Code");
  }

  void _analyseBuildStep(BuildStep buildStep) {
    print("buildStep:${buildStep.inputId.toString()}\n");
  }

  void _analyseAnnotation(ConstantReader annotation) {
    print("params: ${annotation.read("name")}\n");
    print("params: ${annotation.read("age")}\n");
  }

  void _analyseElement(Element element) {
    print("ElementKind:${element.kind.name}\n");
    switch (element.kind) {
      case ElementKind.CLASS:
        _analyseElementForClass(element);
        break;
      case ElementKind.FUNCTION:
        _analyseElementForMethod(element);
        break;
      default:
        break;
    }
  }

  void _analyseElementForClass(Element element) {
    var e = element as ClassElement;
    e.fields.forEach((element) {
      print("字段:${element.declaration}\n");
    });
    e.methods.forEach((element) {
      print("方法:${element.declaration}");
    });
  }

  void _analyseElementForMethod(Element element) {
    print(
        "方法名称:${element.name},方法参数:${(element as FunctionElement).parameters[0].declaration}");
  }

  template(String className, String content) {
    return """ 
      class ${className}{
        /**
        $content
        */
      }
    """;
  }
}